<?php
require_once '../config/config.php';
require_once LIBS_DIR . 'functions.php';
require_once LIBS_DIR . 'classes/class.DataSource.php';
require_once LIBS_DIR . 'classes/class.Table.php';
require_once LIBS_DIR . 'classes/class.Template.php';

session_start();
// echo session_id();
// unset( $_SESSION['basket']);
if (!isset($_SESSION['basket']['total_price'])) $_SESSION['basket']['total_price'] = 0;
if (!isset($_SESSION['basket']['total_amount'])) $_SESSION['basket']['total_amount'] = 0;

if (!empty($_GET['delete_product']) && !empty($_GET['product_id']) && !empty($_GET['product_price']) && isset($_SESSION['basket']['order'][$_GET['product_id']]) )
{
	$_SESSION['basket']['total_amount'] -= $_SESSION['basket']['order'][$_GET['product_id']];
	$_SESSION['basket']['total_price'] -= $_GET['product_price']*$_SESSION['basket']['order'][$_GET['product_id']];
	unset($_SESSION['basket']['order'][$_GET['product_id']]);
	die(json_encode(array(
			'total_amount'	=> $_SESSION['basket']['total_amount'],
			'total_price'	=> $_SESSION['basket']['total_price']
	)));
}

if (!empty($_GET['calculate_basket']) && !empty($_GET['product_id']) && !empty($_GET['product_price']))
{
	if (isset($_SESSION['basket']['order'][$_GET['product_id']]))
	{
		$product_amount_diff = $_GET['product_amount'] - $_SESSION['basket']['order'][$_GET['product_id']];
		$_SESSION['basket']['total_price'] += $product_amount_diff*$_GET['product_price'];
		$_SESSION['basket']['total_amount'] += $product_amount_diff;
		$_SESSION['basket']['order'][$_GET['product_id']] = $_GET['product_amount']; //Changes amount of selected product
		
	}
	die(json_encode(array(
			'total_amount'	=> $_SESSION['basket']['total_amount'],
			'total_price'	=> $_SESSION['basket']['total_price']
	)));
}


if (!empty($_GET['fill_basket']) && !empty($_GET['product_id']) && !empty($_GET['product_price']))
{
	$_SESSION['basket']['total_price'] += $_GET['product_price'];
	$_SESSION['basket']['total_amount']++;
	if (!empty($_SESSION['basket']['order'][$_GET['product_id']])){
		$_SESSION['basket']['order'][$_GET['product_id']]++;
	}
	else{
		$_SESSION['basket']['order'][$_GET['product_id']] = 1;
	}
	die(json_encode(array(
			'total_amount'	=> $_SESSION['basket']['total_amount'],
			'total_price'	=> $_SESSION['basket']['total_price']
	)));
}


// echo "<pre>";
// print_r($_SESSION);
// echo "</pre>";


$tpl = new Template(FRONT_DIR . 'front.html.php');
$_tpl = new Template(FRONT_DIR . CMD . '/' . CMD . '.html.php');

require_once CMD . '/' . CMD . '.php';

// if (isset($_POST['login'])) echo 1;

$category = new Table('category');
$category->select(  array(
						array('status', 'ON', '=')));
$categories = array();

if ($category->hierarch){
	$categories = get_hierarch($category);
}

$tpl->set(array(
	'categories'	=> $categories,
	'content'	=> $_tpl
));
echo $tpl->fetch();
?>